package swarch.messageflow;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnection;
import org.apache.log4j.Logger;
import org.apache.servicemix.components.util.ComponentSupport;
import org.apache.servicemix.jbi.listener.MessageExchangeListener;

public class MissionRepositoryBean extends ComponentSupport implements
		MessageExchangeListener {

	private final static Logger logger = Logger
			.getLogger(MissionRepositoryBean.class);
	@Resource
	private DeliveryChannel channel;

	public void onMessageExchange(MessageExchange exchange)
			throws MessagingException {
		
//		String strDestination = (String) inMessage.getProperty("Destination");
		String strDestination = "swarch.mission.output";
		
		logger.info("Destination: " + strDestination);

		ActiveMQConnection connection = null;
		try {
			connection = ActiveMQConnection
					.makeConnection("tcp://localhost:61616");
			
			connection.start();
			Session session = connection.createSession(false,
					Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue(strDestination);
			ObjectMessage simpleMessage = session.createObjectMessage();
			
			List<Mission> missionList = MissionHelper.findAllMission();
			
			simpleMessage.setObject((ArrayList<Mission>)missionList);

			MessageProducer producer = session.createProducer(destination);
			producer.send(simpleMessage);

			logger.info("send message to '" + strDestination + "'");
		} catch (JMSException e1) {
			e1.printStackTrace();
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		}
		
//		NormalizedMessage outMessage = exchange.createMessage();
//    	try {
//    		outMessage.setContent(new StringSource(MissionMessageHelper.marshallQuote(missionList)));
//    	} catch(Exception e) {
//    		logger.error("error setting content on cheapest bookstore response message", e);
//    	}
//        exchange.setMessage(outMessage, "out");
		
		exchange.setStatus(ExchangeStatus.DONE);
		channel.send(exchange);
	}
}
